// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    const navLinks = document.querySelectorAll('nav ul li a');

    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href').slice(1);
            document.querySelectorAll('section').forEach(section => {
                section.style.display = 'none';
            });
            document.getElementById(targetId).style.display = 'block';
        });
    });

    const sqlButton = document.querySelector('.sql-editor button');
    const queryResult = document.querySelector('.query-result table tbody');
    // 1. 加载数据库列表
    function loadDataSources() {
        fetch('/api/db/dataTables')
            .then(res => {
                if (!res.ok) throw new Error('获取数据库列表失败');
                return res.json();
            })
            .then(dbs => {
                const dataSourceList = document.getElementById('dataSourceList');
                dataSourceList.innerHTML = '';
                dbs.forEach(db => {
                    const li = document.createElement('li');
                    li.textContent = db;
                    li.addEventListener('click', () => {
                        // 在数据库点击事件中添加
                        document.querySelectorAll('#dataSourceList li').forEach(l => l.classList.remove('active'));
                        li.classList.add('active');
                        dbConnection.currentDb = dbName;
                    });
                    dataSourceList.appendChild(li);
                });
                // 默认选中第一个数据库
                if (dbs.length > 0) {
                    dataSourceList.firstChild.click();
                }
            })
            .catch(err => {
                console.error(err);
                document.getElementById('dataSourceList').innerHTML = '<li style="color:red;">加载数据库失败</li>';
            });
    }
    // 添加载入表按钮事件
    document.querySelector('.db-select button').addEventListener('click', function() {
        const selectedDb = document.querySelector('#dataSourceList li.active');
        if (selectedDb) {
            loadTables(selectedDb.textContent);
        } else {
            alert('请先选择数据库');
        }
    });
    // 获取数据库列表
    // 2. 加载指定数据库的表列表（使用 form-data 请求方式）
    // 修复后的loadTables函数
    // 存储表结构信息
    const tableStructures = {};
    const selectedTables = new Set();

    // 修改 loadTables 函数，添加表多选逻辑
    function loadTables(dbName) {
        const formData = new FormData();
        formData.append('dbName', dbName);

        fetch('/api/db/tables', { method: 'POST', body: formData })
            .then(res => {
                if (!res.ok) throw new Error('获取表列表失败');
                return res.json();
            })
            .then(tables => {
                const tableList = document.getElementById('tableList');
                tableList.innerHTML = '';
                tables.forEach(table => {
                    const li = document.createElement('li');
                    li.textContent = table;
                    if (selectedTables.has(table)) li.classList.add('active');
                    li.addEventListener('click', () => {
                        if (selectedTables.has(table)) {
                            selectedTables.delete(table);
                            li.classList.remove('active');
                            delete tableStructures[table];
                        } else {
                            selectedTables.add(table);
                            li.classList.add('active');
                            loadTableStructure(table);
                        }
                        renderTableStructures();
                        updateSelectedTablesList();
                    });
                    tableList.appendChild(li);
                });
            })
            .catch(err => {
                console.error(err);
                document.getElementById('tableList').innerHTML = '<li style="color:red;">加载表列表失败</li>';
            });
    }

    // 渲染已选表结构，多列横向展示
    function renderTableStructures() {
        const container = document.getElementById('tableStructures');
        container.innerHTML = '';
        selectedTables.forEach(table => {
            const struct = tableStructures[table] || [];
            let html = `<div class="table-struct-col"><h4>${table}</h4><table><thead><tr><th>名称</th><th>类型</th><th>主键</th></tr></thead><tbody>`;
            struct.forEach(col => {
                html += `<tr><td>${col.Field || ''}</td><td>${col.Type || ''}</td><td>${col.Key || ''}</td></tr>`;
            });
            html += '</tbody></table></div>';
            container.innerHTML += html;
        });
    }

    // 修改 loadTableStructure 函数，存储表结构并渲染
    function loadTableStructure(tableName) {
        fetch(`/api/db/table/${tableName}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (!data || !Array.isArray(data)) {
                    throw new Error('返回的数据格式不正确');
                }
                tableStructures[tableName] = data;
                renderTableStructures();
            })
            .catch(error => {
                console.error('加载表结构失败:', error);
                tableStructures[tableName] = [{Field: '加载失败', Type: '', Key: ''}];
                renderTableStructures();
            });
    }

    // 更新已选表列表显示
    function updateSelectedTablesList() {
        const selectedTablesList = document.getElementById('selectedTablesList');
        selectedTablesList.innerHTML = '';
        selectedTables.forEach(table => {
            const li = document.createElement('li');
            li.textContent = table;
            selectedTablesList.appendChild(li);
        });
    }

    // 清空SQL输入框
    const clearBtn = document.getElementById('clearSql');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            document.getElementById('sqlTextarea').value = '';
        });
    }

    //生成sql
    // 初始化时绑定生成SQL按钮事件
    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('generateSqlBtn').addEventListener('click', generateSql);
    });
    // 生成SQL逻辑
    function generateSql() {
        const prompt = document.getElementById('promptInput').value.trim();
        if (!prompt) {
            alert('请输入生成SQL的提示');
            return;
        }
        if (selectedTables.size === 0) {
            alert('请选择至少一个表');
            return;
        }

        // 收集选中表的结构信息
        const selectedTablesInfo = {};
        selectedTables.forEach(table => {
            selectedTablesInfo[table] = tableStructures[table] || [];
        });

        fetch('/api/db/generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                prompt: prompt,
                selectedTablesInfo: selectedTablesInfo
            })
        })
            .then(res => {
                if (!res.ok) throw new Error('生成SQL失败');
                return res.json();
            })
            .then(data => {
                document.getElementById('sqlTextarea').value = data.sql || '';
            })
            .catch(err => {
                console.error('生成SQL失败:', err);
                document.getElementById('sqlTextarea').value = '生成SQL失败，请检查输入或网络';
            });
    }

    // 执行SQL查询
    document.querySelector('#executeSql').addEventListener('click', function() {
        const sql = document.querySelector('.sql-editor textarea').value;
        fetch('/api/db/execute', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({sql: sql})
        })
            .then(response => response.json())
            .then(result => {
                console.log('渲染数据', result);
                const resultContainer = document.getElementById('queryResultContainer');
                resultContainer.innerHTML = '';
                if (!result.success) {
                    resultContainer.innerHTML = `<div class="error">查询失败：${result.error || '未知错误'}</div>`;
                    return;
                }
                const data = result.data || [];
                const columns = result.columns || [];
                if (data.length === 0) {
                    resultContainer.innerHTML = '<div>无数据</div>';
                    return;
                }
                let html = '<table class="result-table"><thead><tr>';
                columns.forEach(col => {
                    html += `<th>${col}</th>`;
                });
                html += '</tr></thead><tbody>';
                data.forEach(row => {
                    html += '<tr>';
                    columns.forEach(col => {
                        html += `<td>${row[col]}</td>`;
                    });
                    html += '</tr>';
                });
                html += '</tbody></table>';
                resultContainer.innerHTML = html;
            })
            .catch(err => {
                document.getElementById('queryResultContainer').innerHTML = `<div class="error">请求异常：${err}</div>`;
            });
    });
    // 页面加载完成后初始化数据库列表
    loadDataSources();
    const generateBtn = document.getElementById('generateSqlBtn');
    if (generateBtn) {
        generateBtn.addEventListener('click', generateSql);
    }

});
function handleUpload() {
    const fileInput = document.getElementById('xmindFile');
    const templateType = document.getElementById('templateType').value;

    if (!fileInput.files[0]) {
        alert('请选择XMind文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('templateType', templateType);

    fetch('/xmindToExcel/importFile', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            // 将成功信息写入到 <textarea> 中
            const responseTextarea = document.getElementById('xmindResponse');
            responseTextarea.value = '转换成功: ' + JSON.stringify(data);
            // 直接提取 excelUrl
            if (data && data.excelUrl) {
                sessionStorage.setItem('excelUrl', data.excelUrl);
                document.getElementById('downloadBtn').disabled = false;
            } else if (data && data.message && data.message.excelUrl) {
                sessionStorage.setItem('excelUrl', data.message.excelUrl);
                document.getElementById('downloadBtn').disabled = false;
            } else {
                document.getElementById('downloadBtn').disabled = true;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('上传失败: ' + error.message);
        });
}

function handleDownload() {
    const excelUrl = sessionStorage.getItem('excelUrl');
    if (!excelUrl) {
        alert('没有可下载的Excel文件');
        return;
    }
    // 直接用COS url下载
    const a = document.createElement('a');
    a.href = excelUrl;
    a.download = '';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

// ========== 测试点生成工具相关 ===========
// 预览xmind文件
function previewXmindFile(url) {
    // 加时间戳防缓存
    const previewUrl = url + (url.includes('?') ? '&' : '?') + '_t=' + Date.now();
    const container = document.getElementById('xmindPreviewContainer');
    // 让容器宽高100%，高度自适应父容器
    container.style.width = '100%';
    // 取父容器高度
    const parent = container.parentElement;
    if (parent) {
        const parentHeight = parent.clientHeight;
        if (parentHeight > 0) {
            container.style.height = parentHeight + 'px';
        } else {
            container.style.height = '500px'; // 兜底
        }
    } else {
        container.style.height = '500px';
    }
    fetch(previewUrl)
        .then(res => res.arrayBuffer())
        .then(file => {
            container.innerHTML = '';
            const viewer = new window.XMindEmbedViewer({
                el: '#xmindPreviewContainer',
                style: { width: '100%', height: '100%' }
            });
            setTimeout(() => {
                const inner = container.querySelector('div');
                if (inner) {
                    inner.style.width = '100%';
                    inner.style.height = '100%';
                }
            }, 100);
            viewer.load(file);
        })
        .catch(err => {
            container.innerHTML = '预览失败：' + err + '<br>请确认文件已生成且为有效的xmind文件。';
        });
}

// 判断文件类型
function getFileType(fileName) {
    const extension = fileName.toLowerCase().split('.').pop();
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(extension)) {
        return 'image';
    } else if (['doc', 'docx'].includes(extension)) {
        return 'document';
    } else {
        return 'unknown';
    }
}

// 文件上传
function handleTestPointUpload(requirement) {
    const fileInput = document.getElementById('testPointFile');
    if (!fileInput.files[0]) {
        alert('请选择需求文档文件');
        return;
    }
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    if (requirement) {
        formData.append('requirement', requirement);
    }
    fetch('/testpoint/generate', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            const resultDiv = document.getElementById('testPointResult');
            const msgP = document.getElementById('testPointMsg');
            const downloadBtn = document.getElementById('downloadTestPointBtn');
            if (data.success) {
                msgP.textContent = '测试点生成成功！';
                downloadBtn.disabled = false;
                downloadBtn.dataset.url = data.downloadUrl;
                // 自动预览xmind
                previewXmindFile(data.downloadUrl);
            } else {
                msgP.textContent = '生成失败：' + (data.error || '未知错误');
                downloadBtn.disabled = true;
                downloadBtn.dataset.url = '';
                document.getElementById('xmindPreviewContainer').innerHTML = '';
            }
            resultDiv.style.display = 'block';
        })
        .catch(err => {
            alert('请求失败: ' + err);
        });
}

//文件下载
function handleTestPointDownload() {
    const downloadBtn = document.getElementById('downloadTestPointBtn');
    const url = downloadBtn.dataset.url;
    if (!url) {
        alert('没有可下载的文件');
        return;
    }
    // 提取文件名参数
    const fileParam = url.split('?file=')[1];
    if (!fileParam) {
        alert('下载链接无效');
        return;
    }
    // GET下载，直接跳转/api/download接口
    const downloadUrl = '/fileconfig/download?file=' + encodeURIComponent(fileParam);
    fetch(downloadUrl)
        .then(response => {
            if (!response.ok) throw new Error('下载失败');
            return response.blob();
        })
        .then(blob => {
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = fileParam;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(a.href);
        })
        .catch(err => {
            alert('下载失败，请确认文件已生成且为有效的xmind文件。');
        });
}

// 上传文件，返回文件名
function uploadTestFile(callback) {
    const fileInput = document.getElementById('testPointFile');
    if (!fileInput.files[0]) {
        alert('请选择需求文档文件');
        return;
    }
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    fetch('/fileconfig/fileupload', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.fileName) {
                callback(data.fileName);
            } else {
                alert('文件上传失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(err => {
            alert('文件上传失败: ' + err);
        });
}

// 生成测试点，根据文件类型调用不同的API
function generateTestPoints(fileName, promot, callback) {
    window.lastUploadedFileName = fileName; // 记录最近一次上传的文件名
    const fileType = getFileType(fileName);
    const done = function() { if (typeof callback === 'function') callback(); };
    if (fileType === 'image') {
        // 图片文件调用imageUpload接口
        const fileInput = document.getElementById('testPointFile');
        const formData = new FormData();
        formData.append('file', fileInput.files[0]);
        if (promot) {
            formData.append('promot', promot);
        }
        fetch('/api/imageUpload', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                handleTestPointResponse(data);
                done();
            })
            .catch(err => {
                alert('请求失败: ' + err);
                done();
            });
    } else if (fileType === 'document') {
        // 文档文件调用wordUpload接口
        const formData = new FormData();
        formData.append('fileName', fileName);
        if (promot) {
            formData.append('promot', promot);
        }
        fetch('/api/wordUpload', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                handleTestPointResponse(data);
                done();
            })
            .catch(err => {
                alert('请求失败: ' + err);
                done();
            });
    } else {
        alert('不支持的文件类型，请上传图片(.jpg, .png等)或文档(.doc, .docx)文件');
        done();
    }
}

// 处理测试点生成响应
function handleTestPointResponse(data) {
    const resultDiv = document.getElementById('testPointResult');
    const msgP = document.getElementById('testPointMsg');
    const downloadBtn = document.getElementById('downloadTestPointBtn');

    if (data.success) {
        msgP.textContent = '测试点生成成功！';
        downloadBtn.disabled = false;
        downloadBtn.dataset.url = data.downloadUrl;
        // 只在xmindPreviewContainer预览区显示xmind，不切换tab
        if (data.downloadUrl) {
            previewXmindFile(data.downloadUrl);
        }
    } else {
        msgP.textContent = '生成失败：' + (data.error || '未知错误');
        downloadBtn.disabled = true;
        downloadBtn.dataset.url = '';
        document.getElementById('xmindPreviewContainer').innerHTML = '';
    }
    resultDiv.style.display = 'block';
}

function setGenerateBtnLoading(loading) {
    const genBtn = document.getElementById('generateTestPointBtn');
    if (genBtn) {
        if (loading) {
            genBtn.disabled = true;
            genBtn.textContent = '生成中...';
        } else {
            genBtn.disabled = false;
            genBtn.textContent = '生成测试点';
        }
    }
}

// 生成测试点按钮事件，默认promot
function handleGenerateBtn() {
    const defaultPromot = '请根据上传的需求文档自动提取所有功能点并生成详细的测试点，要求结构化、分层级、覆盖全面。';
    setGenerateBtnLoading(true);
    uploadTestFile(function(fileName) {
        generateTestPoints(fileName, defaultPromot, function() {
            setGenerateBtnLoading(false);
        });
    });
}

function setRegenerateBtnLoading(loading) {
    const regenBtn = document.getElementById('regenerateBtn');
    if (regenBtn) {
        if (loading) {
            regenBtn.disabled = true;
            regenBtn.textContent = '生成中...';
        } else {
            regenBtn.disabled = false;
            regenBtn.textContent = '重新生成';
        }
    }
}
// 重新生成按钮事件，使用输入框内容
function handleRegenerateBtn() {
    const promot = document.getElementById('regenerateInput').value;
    if (!promot) {
        alert('请输入新的生成要求');
        return;
    }
    // 直接用上次上传的文件名
    const lastFileName = window.lastUploadedFileName;
    if (!lastFileName) {
        alert('请先上传文件并生成一次测试点');
        return;
    }
    setRegenerateBtnLoading(true);
    generateTestPoints(lastFileName, promot, function() {
        setRegenerateBtnLoading(false);
    });
}

document.addEventListener('DOMContentLoaded', function() {
    const genBtn = document.getElementById('generateTestPointBtn');
    if (genBtn) {
        genBtn.addEventListener('click', handleGenerateBtn);
    }
    const dlBtn = document.getElementById('downloadTestPointBtn');
    if (dlBtn) {
        dlBtn.addEventListener('click', handleTestPointDownload);
    }
    // 重新生成按钮
    const regenBtn = document.getElementById('regenerateBtn');
    if (regenBtn) {
        regenBtn.addEventListener('click', handleRegenerateBtn);
    }
});